import { ESJVector3D } from "earthsdk3";
import { Destroyable, reactArrayWithUndefined, track } from "xbsj-base";
import { MultiPointsEditing } from ".";
import { GeoCanvasMenuPoi } from "@czmSrc/index";

let lastId = 0;
// 用于显示点的类，编辑和修改过程中，点的形式不同,在追加和插值中各自实现派生类
export class EditingPoint extends Destroyable {
    private _position = this.disposeVar(reactArrayWithUndefined<ESJVector3D>(undefined));
    get position() { return this._position.value; }
    set position(value: ESJVector3D | undefined) { this._position.value = value; }
    get positionChanged() { return this._position.changed; }

    private _id = lastId++;
    get id() { return this._id }

    private _menuPoi;
    get menuPoi() { return this._menuPoi; }
    constructor(multiPointsEditing: MultiPointsEditing, position?: ESJVector3D) {
        super();
        // 初始化位置赋值
        position && (this.position = position);
        multiPointsEditing.debug && console.log(`PolylinePositionEditor creating! ${this.id}`);
        this.dispose(() => { multiPointsEditing.debug && console.log(`PolylinePositionEditor destroying! ${this.id}`); });
        const menuPoi = this._menuPoi = this.ad(new GeoCanvasMenuPoi(multiPointsEditing.czmViewer));
        menuPoi.enabled = false;
        this.ad(track([menuPoi, 'show'], [multiPointsEditing, 'enabled']));
        {
            const update = () => {
                if (this.position === undefined) {
                    menuPoi.position = undefined;
                    return;
                }
                const tempPos = [...this.position] as [number, number, number];
                tempPos[2] -= multiPointsEditing.czmViewer.editingHeightOffset ?? 0;
                menuPoi.position = tempPos;
                multiPointsEditing.positionsChanged.emit();
            }
            update()
            this.d(this.positionChanged.don(update));
        }
        {
            const update = () => {
                const index = multiPointsEditing.editingPoints.indexOf(this) + 1;
                if (index === 0) return;
                menuPoi.title = `控制点${index}`;
                if (index === 1) {
                    menuPoi.imageUri = multiPointsEditing.firstControlPointImageUrl ?? MultiPointsEditing.defaults.firstControlPointImageUrl;
                } else {
                    menuPoi.imageUri = multiPointsEditing.otherControlPointImageUrl ?? MultiPointsEditing.defaults.otherControlPointImageUrl;
                }
            }
            update();
            this.dispose(multiPointsEditing.editingPoints.changedEvent.disposableOn(update));
        }
    }
}